package com.cloudwise.gproject.service.impl;

import com.cloudwise.gproject.dao.UserRoleDao;
import com.cloudwise.gproject.entity.Role;
import com.cloudwise.gproject.entity.User;
import com.cloudwise.gproject.entity.UserRole;
import com.cloudwise.gproject.service.RoleService;
import com.cloudwise.gproject.service.UserRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户和角色关联表(UserRole)表服务实现类
 *
 * @author makejava
 * @since 2021-03-24 15:58:51
 */
@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {
    @Resource
    private UserRoleDao userRoleDao;
    @Resource
    private RoleService roleService;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public List<UserRole> queryById(Integer userId) {
        return this.userRoleDao.queryById(userId);
    }

    /**
     * 查询多条数据
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<UserRole> queryAllByLimit(int offset, int limit) {
        return this.userRoleDao.queryAllByLimit(offset, limit);
    }

    /**
     * 根据user添加userRole
     * @param user
     * @return
     */
    @Override
    public List<UserRole> insert(User user) {
        List<UserRole> userRoleList = new ArrayList<>();
        for (String roleName : user.getRoleNames()) {
            //根据roleName获取相应role
            Role role = new Role();
            role.setRoleName(roleName);
            Role role1 = roleService.queryAllWithoutLimit(role).get(0);
            //将数据加入userRole表
            UserRole userRole = new UserRole();
            userRole.setRoleId(role1.getRoleId());
            userRole.setUserId(user.getUserId());
            try {
                userRoleDao.insert(userRole);
            } catch (Exception e) {
            }
            userRoleList.add(userRole);
        }
        return userRoleList;
    }

    /**
     * 修改数据
     *
     * @param userRole 实例对象
     * @return 实例对象
     */
    @Override
    public UserRole update(UserRole userRole) {
        this.userRoleDao.update(userRole);
        return this.queryById(userRole.getUserId()).get(0);
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userRoleDao.deleteById(userId) > 0;
    }

    /**
     * 通过实体作为筛选条件分页查询
     *
     * @param userRole 实例对象
     * @return 对象列表
     */
    @Override
    public PageInfo queryAll(int pageNo, int pageSize, UserRole userRole) {
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<UserRole>(this.userRoleDao.queryAll(userRole));
    }
}
